<?php

class MailConversationController extends GxController {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('sendMailTouser'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('inbox', 'sendMailTouser', 'GetMessage'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionsendMailTouser() {
        if (isset($_POST['makeQueryId']) && $_POST['makeQueryId'] <> "") {
            $modelMake = MakeQuery::model()->findByPk($_POST['makeQueryId']);
            $modelMake->setAttribute('mail_sent', SkillConfig::STATUS_ACTIVE);
            $modelMake->save();
        }
        if (isset($_POST['msgval'])) {
            if ($_POST['type'] != 'course') {
                $courseClassId = 'classes_id';
                $classes = Classes::model()->findByPk($_POST['classId']);
                $classCourseName = $classes->class_titile;
            } else {
                $courseClassId = 'courses_id';
                $classes = Courses::model()->findByPk($_POST['classId']);
                $classCourseName = $classes->course_titile;
            }

            $arrayVal = explode(',', $_POST['selectedUser']);
            foreach ($arrayVal as $userVal) {
                $model = new MailConversation;
                $model->setAttribute($courseClassId, $_POST['classId']);
                $model->setAttribute('to_user_id', $userVal);
                $model->setAttribute('mail_subject', $_POST['subject']);
                $model->setAttribute('mail_message', $_POST['msgval']);
                $model->setAttribute('from_users_id', getLoginUserId());
                $model->setAttribute('created_time', SkillConfig::CreateDateTime());
                $userdetails = Users::getFrontEndUser($userVal);
                $trainername = Users::getFrontEndUser(getLoginUserId());
                $model->save();
                $mailmodel = EmailTemplate::model()->findByPk(Message::CLASS_COURSE_QUERY_NOTIFICATION);
                $userText = $mailmodel->body;
                $mailbody = array('value' => $userText, 'type' => 'raw');
                $userName = $userdetails->first_name . ' ' . $userdetails->last_name;
                $trainernames = $trainername->first_name . ' ' . $trainername->last_name;
                $mailto = $userdetails->user->username;
                $classCourseViewdetailsLink = 'http://' . $_SERVER['HTTP_HOST'] . $this->createUrl('mailConversation/inbox/');
                $arrayFind = array('[username]', '[from_user_name]', '[classcoursename]', '[classCourseViewdetailsLink]');
                $arrayReplace = array($userName, $trainernames, $classCourseName, $classCourseViewdetailsLink);
                $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
                $mailtemp = Template::model()->findByPk($mailmodel->template_id);
                $subject = $mailmodel->subject;
                $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);
                try {
                    SkillSendMail::SendMail($mailto, $subject, $body);
                    $result = 'success';
                } catch (Exception $e) {
                    $result = $e;
                    exit;
                }
            }
            if ($result == 'success') {
                echo 'success';
            }
            Yii::app()->end();
        }
    }

    public function actionInbox() {
        $this->layout = 'detailspage';
        $criteria = new CDbCriteria;
        $criteria->group = 'from_users_id';
        $criteria->condition = 'to_user_id = ' . getLoginUserId();
        $inboxAll = MailConversation::model()->findAll($criteria);

        $backenduserDetails = '';
        $criteriaadmin = new CDbCriteria;
        $criteriaadmin->condition = 'from_users_id = ' . getLoginUserId();
        $inboxAlladmin = ContactAdmin::model()->findAll($criteriaadmin);
        $backenduserDetails = Profiles::model()->findByAttributes(array('user_id' => Message::ADMIN_ID));


        $this->render('inbox', array('inboxAll' => $inboxAll, 'inboxAlladmin' => $inboxAlladmin, 'backenduserDetails' => $backenduserDetails));
    }

    public function actionGetMessage() {
        $userdata = "";
        $criteria = new CDbCriteria;
        $criteria->condition = '(to_user_id = ' . $_POST['touid'] . ' AND from_users_id =' . $_POST['fromuid'] . ') OR (to_user_id = ' . $_POST['fromuid'] . ' AND from_users_id = ' . $_POST['touid'] . ') AND classes_id=' . $_POST['classid'];
        $dataByUser = MailConversation::model()->findAll($criteria);

        echo '<p class="query-name">' . $dataByUser[0]->classes->class_titile . '</p><p class="subject-head"><span>Subject:</span> ' . $dataByUser[0]->mail_subject . '</p><div class="height1px dash-borB addmarginB20 rempaddingB"></div><div class="commentBox"><ol>';
        $totalCount = count($dataByUser) - 1;
        for ($i = 0; $i < count($dataByUser); $i++) {
            $userDetails = Profiles::model()->findByAttributes(array('user_id' => $dataByUser[$i]->from_users_id));
            $imagePath = $dataByUser[$i]->from_users_id;
            if ($userDetails->photo <> "") {
                $imgsrc = baseUrl() . '../../' . getUploadDir() . $imagePath . '/profile/minithumb/' . $userDetails->photo;
            } else {
                $imgsrc = baseUrl() . '../../upload/default-mini.png';
            }

            $userdata.='<li><div class="padding"><div class="user-info borB"><p><img class="user-img" src="' . $imgsrc . '" title="' . $userDetails->first_name . '" alt="' . $userDetails->first_name . '" />' . $userDetails->first_name . '<p><span class="commentDateStamp">' . date("D, d M Y", convert_datetime($dataByUser[$i]->created_time)) . '</span></p></div><div class="comment"><p>' . $dataByUser[$i]->mail_message . '</p>' . '</div></div></li>';

            if ($totalCount == $i) {
                if ($dataByUser[$i]->classes_id <> "") {
                    $class_course_id = $dataByUser[$i]->classes_id;
                    $classtype = "classes";
                } else {
                    $class_course_id = $dataByUser[$i]->courses_id;
                    $classtype = "courses";
                }
                if ($dataByUser[$i]->from_users_id == getLoginUserId()) {
                    $replUid = $dataByUser[$i]->to_user_id;
                } else {
                    $replUid = $dataByUser[$i]->from_users_id;
                }
                $resulData = $userdata . $sendMsgBlock = '</ol></div>
					<input type="hidden" name="" id="subject_id" value="' . $dataByUser[$i]->mail_subject . '">
					<div id="send_a_msg_box" class="reply-box">
					<textarea  id="message_text_id" name="message_text"></textarea>
					<div  class="errorMessage" id="errorMessage_msg_id"></div>
					<div class="clear"></div>
					</div>												
					<p class="alignR remmarginB">
					<input type="button" value="Submit" name="yt1" class="btnbook" onclick="return replyAMailToUser(\'' . $classtype . '\',' . $class_course_id . ',' . $replUid . ',' . getLoginUserId() . ')"></p>
					</div>';
            }
        }
        echo $resulData;
    }

}